<template>
  <div class="view-container">
    <div class="main-content">
      <div class="list-container">
        <div
          class="filter-container"
          style="padding-top:0px"
        >
          <el-row
            :gutter="40"
            style="margin: 0px"
          >
            <el-col
              :lg="20"
              style="padding: 0px"
            >
              <el-form
                :inline="true"
                :model="filterData"
                label-position="right"
                size="small"
                class="filter-form-inline"
              >
                <el-row
                  :gutter="40"
                  style="margin-left: 0px; margin-right: 0px"
                >
                  <el-col
                    :span="6"
                  >
                    <el-form-item
                      label="市场准入状态"
                      style="width: 100%"
                    >
                      <el-select
                        v-model="formData.chanceStatus"
                        clearable
                        style="width: 100%"
                        placeholder="市场准入状态"
                      >
                        <el-option
                          v-for="item in chanceStatus"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                      label="关键字"
                      style="width: 100%"
                    >
                      <el-input
                        v-model="formData.keyWord"
                        clearable
                        placeholder="输入产品名称、通用名、批准文号关键字查询"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="4"
                  >
                    <el-form-item style="width: 100%">
                      <more-search-btn v-model:is-more="visible" />
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item style="width: 100%">
                      <el-button
                        class="border-btn"
                        @click="reset"
                      >重置</el-button>
                      <el-button
                        type="primary"
                        class="main-btn"
                        @click="search"
                      >搜索</el-button>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row
                  v-if="visible"
                  :gutter="40"
                  style="margin-left: 0px; margin-right: 0px"
                >
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                      label="准入地区"
                      style="width: 100%"
                    >
                      <el-cascader
                        ref="cascader"
                        v-model="formData.regionCode"
                        :popper-append-to-body="false"
                        style="width: 100%"
                        :options="citys"
                        :props="props1"
                        placeholder="请选择地区"
                        collapse-tags
                        clearable
                        @change="areaChange"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                      label="准入模式"
                      style="width: 100%"
                    >
                      <el-select
                        v-model="formData.accessMode"
                        clearable
                        style="width: 100%"
                        placeholder="准入模式"
                      >
                        <el-option
                          v-for="item in accessOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                      label="适用终端"
                      style="width: 100%"
                    >
                      <el-select
                        v-model="formData.terminalType"
                        clearable
                        style="width: 100%"
                        placeholder="适用终端"
                      >
                        <el-option
                          v-for="item in appOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                            label="创建人"
                            style="width: 100%"
                    >
                      <el-select
                              v-model="formData.creatorId"
                              clearable
                              style="width: 100%"
                              placeholder="创建人"
                      >
                        <el-option
                                v-for="item in creators"
                                :key="item.id"
                                :label="item.realName"
                                :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="6"
                  >
                    <el-form-item
                            label="价格属性"
                            style="width: 100%"
                    >
                      <el-select
                              v-model="formData.priceProperty"
                              clearable
                              style="width: 100%"
                              placeholder="价格属性"
                      >
                        <el-option
                                v-for="item in priceOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="8"
                  >
                    <el-form-item
                      label="结束日期"
                      style="width: 100%"
                    >
                      <date-range-picker
                              v-model:date="formData.endDate"
                        clearable
                        style="width: 100%;"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col
                          :span="8"
                  >
                    <el-form-item
                      label="创建日期"
                      style="width: 100%"
                    >
                      <date-range-picker
                        v-model:date="formData.createDate"
                        clearable
                        style="width: 100%;"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-col>
          </el-row>
        </div>
        <table-tools>
          <template #left>
            <el-button
                    v-auth="{v: ['crm:chance:pms']}"
              class="main-btn"
              size="small"
              type="primary"
              @click="createChance"
            >新建</el-button>
          </template>
          <template #btn>
            <div style="display: flex; justify-content: flex-end">
              <table-cell-setting
                :checked="checkListData"
                :table-option="tableOption"
                @checkList="checkList"
              />
            </div>
          </template>
        </table-tools>
        <table-view
          header-cell-class-name="table-header"
          :data="listData"
          :visible="visible"
          border
          :cell-style="cellStyle"
          @row-click="rowClick"
        >
          <el-table-column
            show-overflow-tooltip
            prop="chanceNo"
            label="市场准入编号"
            fixed="left"
            :min-width="120"
          />
          <el-table-column
            show-overflow-tooltip
            align="left"
            header-align="center"
            prop="chanceName"
            label="市场准入名称"
            fixed="left"
            :min-width="200"
          />
          <el-table-column
            prop="region"
            align="center"
            label="准入地区"
            :min-width="250"
          >
            <template #default="scope">
              <area-list-view :areas="scope.row.region" />
            </template>
          </el-table-column>
          <el-table-column
            prop="accessMode"
            label="准入模式"
            :min-width="100"
            align="center"
          >
            <template #default="scope">
              {{ getLabel("access_mode", scope.row.accessMode) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="terminalType"
            label="适用终端"
            width="100px"
          >
            <template #default="scope">
              {{ getLabel("app_mode", scope.row.terminalType) }}
            </template>
          </el-table-column>
          <!--          <el-table-column-->
          <!--            prop="productName"-->
          <!--            label="产品名称"-->
          <!--            v-if="checkListData.indexOf('productName') !== -1"-->
          <!--          />-->
          <el-table-column
            show-overflow-tooltip
            align="left"
            prop="productPopularName"
            header-align="center"
            label="产品名称"
            :min-width="150"
          />
          <el-table-column
            show-overflow-tooltip
            prop="productName"
            label="商品名"
            :min-width="150"
          />
          <el-table-column
            show-overflow-tooltip
            prop="packSpecs"
            label="包装规格"
            :min-width="100"
          />
          <el-table-column
                  show-overflow-tooltip
                  prop="producer"
                  label="生产厂家"
                  :min-width="100"
          />
          <el-table-column
            prop="terminalPrice"
            label="终端价（元）"
            align="center"
            :min-width="120"
          />
          <el-table-column
            prop="expireTime"
            label="结束日期"
            :min-width="120"
            align="center"
          >
            <template #default="scope">
              {{ dateFormat("yyyy-mm-dd", scope.row.expireTime) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="createdAt"
            label="创建时间"
            :min-width="150"
            align="center"
          >
            <template #default="scope">
              {{ dateFormat("yyyy-mm-dd HH:MM", scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkListData.indexOf('creatorName') !== -1"
            prop="creatorName"
            label="创建人"
            :min-width="120"
            align="center"
          />
          <el-table-column
            v-if="checkListData.indexOf('priceProperty') !== -1"
            prop="priceProperty"
            label="价格属性"
            :min-width="100"
            align="center"
          >
            <template #default="scope">
              {{ getLabel("price_type", String(scope.row.priceProperty)) }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkListData.indexOf('productAlias') !== -1"
            show-overflow-tooltip
            header-align="center"
            prop="productAlias"
            label="产品别名"
            :min-width="140"
            align="left"
          />
<!--          <el-table-column-->
<!--            v-if="checkListData.indexOf('productName') !== -1"-->
<!--            show-overflow-tooltip-->
<!--            prop="productName"-->
<!--            label="产品商品名"-->
<!--            :min-width="140"-->
<!--            align="left"-->
<!--          />-->

          <el-table-column
            prop="chanceStatus"
            label="市场准入状态"
            :min-width="120"
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <!--              <div v-if="scope.row.flowStatus!=='DOING'">{{ getLabel("chance_status", scope.row.chanceStatus) }}</div>-->
<!--              <div class="tab-line">-->
<!--                <div v-if="scope.row.flowStatus=='DOING'">{{ getLabel('approval_result',scope.row.flowStatus) }}</div>-->

<!--                <div v-else-if="scope.row.flowStatus && scope.row.flowStatus!=='AGREE' && scope.row.flowStatus!=='REPEAL'">-->
<!--                  审核不通过-->
<!--                </div>-->
<!--                <div v-else-if="scope.row.flowStatus=='REPEAL'">-->
<!--                  {{ getLabel('approval_result',scope.row.flowStatus) }}-->
<!--                </div>-->

<!--                <div v-else>{{ getLabel("chance_status", scope.row.chanceStatus) }}</div>-->
<!--              </div>-->
              <div class="tab-line">
                <div>{{ getLabel("chance_status", scope.row.chanceStatus) }}</div>
                <div class="flow-status-color" v-if="scope.row.flowStatus=='REJECT_INITIATOR'">[{{ getLabel('approval_result',scope.row.flowStatus) }}]</div>
              </div>

            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            header-align="center"
            min-width="150"
          >
            <template #default="scope">

              <el-button
                      v-auth="{v: ['crm:chance:pms'],bool:scope.row.chanceStatus == 0 || scope.row.chanceStatus == -1 || scope.row.flowStatus=='REJECT_INITIATOR'}"
                type="text"
                @click="changeChance(scope.row)"
              >编辑</el-button>
<!--              <el-button-->
<!--                      v-auth="{v:['crm:chance:createPlan'],bool:scope.row.chanceStatus == 2}"-->
<!--                type="text"-->
<!--                @click="successPlan(scope.row.id)"-->
<!--              >创建营销规划</el-button>-->
              <el-button
                      v-auth="{v:['crm:chance:end'],bool:scope.row.chanceStatus == 2}"
                type="text"
                @click="overChance(scope.row.id)"
              >结束市场准入</el-button>
              <el-button
                      v-auth="{v: ['crm:chance:pms'],bool:scope.row.chanceStatus == -2 || scope.row.chanceStatus == -1}"
                type="text"
                class="delete-text-btn"
                @click="deleteChance(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </table-view>
        <Pagination
          v-model:page="formData.page"
          v-model:limit="formData.pageSize"
          style="display: flex; justify-content: flex-end"
          :total="total"
          @pagination="getList"
        />
      </div>
    </div>
    <!-- 创建编辑弹框 -->
    <createOrChange
      ref="createChangeDialog"
      :title="title"
      @success="success"
    />

    <createPlanDialog ref="createPlan" />
  </div>
</template>

<script>
import area from '@/utils/area.js'
import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, onMounted, reactive, ref,} from 'vue'
import {useRouter} from 'vue-router'
import {crmStore} from '@CRM/store'

export default defineComponent({
  name: 'BusinessList',
  components: {
    createOrChange: defineAsyncComponent(() =>
      import('../modules/createOrChange.vue')
    ),
    createPlanDialog: defineAsyncComponent(() =>
            import('../modules/createPlanDialog.vue')
    ),
  },
  setup(props, context) {
    const api = inject('api')
    const chanceStatus =
      crmStore.getters['dictionary/getDictionary']['chance_status']
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const createChangeDialog = ref(null)
    var cascader = ref(null)
    var createPlan = ref(null)
    const citys = area
    const props1 = reactive({
      multiple: true,
      expandTrigger: 'hover',
      label: 'regionName',
      value: 'regionCode',
    })
    const modelOptions =
      crmStore.getters['dictionary/getDictionary']['agent_type']
    const appOptions = crmStore.getters['dictionary/getDictionary']['app_mode']
    const priceOptions =
      crmStore.getters['dictionary/getDictionary']['price_type']
    const accessOptions =
      crmStore.getters['dictionary/getDictionary']['access_mode']
    const creators = ref(crmStore.getters['company/getHeadOptions'])
    var visible = ref(false)
    var checkListData = ref([
      'chanceNo',
      'chanceName',
      'region',
      'accessMode',
      'terminalType',
      // 'productName',
      'approvalNumber',
      'packSpecs',
      'terminalPrice',
      'expireTime',
      'create_time',
      'chanceStatus',
      //  'chance_creator',
      //  'chance_attr',
      //  'chance_name',
      //  'chance_shaopname'
    ])
    const checkList = (checked) => {
      checkListData.value = checked
      console.log(checkListData)
    }
    var tableOption = reactive([
      // { key: "chanceNo", value: "准入市场准入编号" },
      // { key: "chanceName", value: "市场准入名称" },
      // { key: "region", value: "准入地区" },
      // { key: "accessMode", value: "准入模式" },
      // { key: "terminalType", value: "适用终端" },
      // // { key: "productName", value: "产品名称" },
      // { key: "productPopularName", value: "产品名称" },
      // { key: "approvalNumber", value: "批准文号" },
      // { key: "packSpecs", value: "包装规格" },
      // { key: "terminalPrice", value: "终端价（元）" },
      // { key: "expireTime", value: "结束日期" },
      // { key: "createdAt", value: "创建时间" },
      // { key: "chanceStatus", value: "市场准入状态" },

      { key: 'creatorName', value: '创建人' },
      { key: 'priceProperty', value: '价格属性' },
      { key: 'productAlias', value: '产品别名' },
      { key: 'productName', value: '产品商品名' },
    ])
    var formList = reactive([
      // {
      //   key: 'status',
      //   label: '市场准入状态',
      //   form_type: 'select',
      //   value: '',
      //   is_search: false,
      //   options:crmStore.getters['dictionary/getDictionary']['chance_status']
      // },
      {
        key: 'area',
        label: '准入地区',
        form_type: 'select',
        value: 0,
        is_search: false,
        options: [
          { label: '河南', value: 0 },
          { label: '陕西', value: 1 },
        ],
      },
      {
        key: 'model',
        label: '准入模式',
        form_type: 'select',
        value: '',
        is_search: false,
        options: crmStore.getters['dictionary/getDictionary']['access_mode'],
      },
      {
        key: 'terminal',
        label: '适用终端',
        form_type: 'select',
        value: '',
        is_search: false,
        options: crmStore.getters['dictionary/getDictionary']['app_mode'],
      },
      {
        key: 'date_range',
        label: '结束日期',
        form_type: 'daterange',
        value: [],
        is_search: false,
        options: [],
      },
      {
        key: 'date',
        label: '创建时间',
        form_type: 'date',
        value: [],
        is_search: false,
        options: [],
      },
      {
        key: 'people',
        label: '创建人',
        form_type: 'select',
        value: '',
        is_search: false,
        options: [
          { label: 'cdd', value: 0 },
          { label: 'cdd1', value: 1 },
          { label: 'cdd2', value: 2 },
        ],
      },
      {
        key: 'attr',
        label: '价格属性',
        form_type: 'select',
        value: '',
        is_search: false,
        options: crmStore.getters['dictionary/getDictionary']['price_type'],
      },
      // {
      //   key: 'name',
      //   label: '关键字',
      //   form_type: 'text',
      //   value: '',
      //   is_search: false,
      //   options: []
      // },
    ])
    var formData = reactive({
      endDate: [],
      createDate: [],
      page: 1,
      pageSize: 20,
      keyWord: '',
      chanceStatus: '',
      accessMode: '',
      terminalType: '',
      regionCode: [],
      region: [],
      startTime: '',
      endTime: '',
      expireTimeStart: '',
      expireTimeEnd: '',
      priceProperty: '',
      creatorName: '',
      creatorId: '',
      CreateSort: '',
      EndSort: '',
      productAlias: '',
      productPopularName: '',
    })
    // onBeforeMount(() => {
    //   getList()
    // })
    const search = () => {
      let startTime = ''
      let endTime = ''
      let expireTimeStart = ''
      let expireTimeEnd = ''
      if (formData.endDate) {
        (expireTimeStart = formData.endDate[0]),
        (expireTimeEnd = formData.endDate[1])
      } else {
        (expireTimeStart = ''), (expireTimeEnd = '')
      }
      if (formData.createDate) {
        startTime = formData.createDate[0]
        endTime = formData.createDate[1]
      } else {
        startTime = ''
        endTime = ''
      }
      formData.chanceStatus = formData.chanceStatus
      formData.keyWord = formData.keyWord
      formData.page = 1
      formData.pageSize = 20
      formData.accessMode = formData.accessMode
      formData.terminalType = formData.terminalType
      formData.region = formData.region
      formData.startTime = startTime
      formData.endTime = endTime
      formData.expireTimeStart = expireTimeStart
      formData.expireTimeEnd = expireTimeEnd
      formData.priceProperty = formData.priceProperty
      formData.creatorId = formData.creatorId
      getList(formData)
    }
    const reset = () => {
      formData.chanceStatus = ''
      formData.keyWord = ''
      formData.page = 1
      formData.pageSize = 20
      formData.accessMode = ''
      formData.terminalType = ''
      formData.region = []
      formData.regionCode = []
      formData.startTime = ''
      formData.endTime = ''
      formData.expireTimeStart = ''
      formData.expireTimeEnd = ''
      formData.priceProperty = ''
      formData.creatorId = ''
      formData.endDate = []
      formData.createDate = []
      getList(formData)
    }
    onMounted(() => {
      getList(formData)
    })
    var listData = ref([])
    var total = ref(0)
    const getList = (val) => {
      api.chance.CHANCE_LIST(val).then((res) => {
        if (res.code == 0) {
          if (res.data.list != null) {
            listData.value = res.data.list
            total.value = res.data.total
          } else {
            listData.value = []
            total.value = res.data.total
          }
        }
        // console.log(listData,total)
      })
    }

    var pager = reactive({
      page_number: 1,
      page_size: 20,
    })
    var title = ref('')
    const createChance = () => {
      console.log(createChangeDialog)
      createChangeDialog.value.open()
      title.value = '新建市场准入'
    }
    var form = reactive({})
    const changeChance = (row) => {
      console.log(row)
      createChangeDialog.value.open(row)
      title.value = '编辑市场准入'
    }
    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      if (column.label === '操作') return
      router.push({
        name: 'chanceDetail',
        query: {
          id: row.id,
        },
      })
    }
    const deleteChance = (id) => {
      console.log(currentInstance.proxy)
      currentInstance.proxy
        .alertBox({
          message: '删除市场准入后将不可恢复，确认删除吗？',
          title: '确认',
        })
        .then(() => {
          api.chance.CHANCE_DELETE(id).then((res) => {
            if (!res.code) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: res.msg,
              })
              getList(formData)
            }
          })
          console.log('确定')
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const overChance = (id) => {
      currentInstance.proxy
        .alertBox({
          message: '结束市场准入后，此市场准入将不能进行操作，确定结束吗？',
          title: '确认',
        })
        .then(() => {
          api.chance.CHANCE_END(id).then((res) => {
            if (!res.code) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: res.msg,
              })
              getList(formData)
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }
    const successPlan = (id) => {
      createPlan.value.openDialog(id)
      // router.push({
      //   name: 'planAdd',
      //   query: {
      //     chance_id: id,
      //   },
      // })
    }
    const success = () => {
      getList(formData)
    }
    const areaChange = (val) => {
      console.log(val)

      const serve = currentInstance.proxy.getServeAreaData(
        val,
        cascader.value.getCheckedNodes()
      )
      console.log(serve)
      formData.region = serve
      console.log('转换服务器地址 ', serve)
      console.log(
        '转换本地地址 ',
        currentInstance.proxy.getCascaderAreaData(serve)
      )
    }

    return {
      form,
      api,
      title,
      formData,
      listData,
      total,
      pager,
      checkListData,
      createChangeDialog,
      createPlan,
      createChance,
      cellStyle,
      rowClick,
      checkList,
      deleteChance,
      overChance,
      successPlan,
      changeChance,
      formList,
      tableOption,
      chanceStatus,
      getList,
      success,
      search,
      reset,
      visible,
      cascader,
      citys,
      props1,
      modelOptions,
      appOptions,
      priceOptions,
      accessOptions,
      areaChange,
      creators,
    }
  },
})
</script>
